package com.kaesar.thread_ressmix.atomic;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: chengk
 * @Date: 2021/8/30 7:53 下午
 */
public class AtomicIntegerTest {
    /**
     * 如果不使用AtomicInteger，使用原始的int或Integer，最终结果值可能会小于10000（并发时读到了过时的数据或存在值覆盖的问题）
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger();

        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new Accumlator(atomicInteger), "thread-" + i);
            list.add(t);
            t.start();
        }

        for (Thread t : list) {
            t.join();
        }
        System.out.println(atomicInteger.get());
    }

    static class Accumlator implements Runnable {
        private AtomicInteger atomicInteger;

        Accumlator(AtomicInteger atomicInteger) {
            this.atomicInteger = atomicInteger;
        }

        @Override
        public void run() {
            for (int i = 0, len = 10000; i < len; i++) {
                atomicInteger.incrementAndGet();
            }
        }
    }
}
